﻿$(function () {
    layui.use(['element', 'notice', 'layer', 'laytpl', 'tree', 'treeTable', 'form', 'iziToast'], function () {
        var layer = layui.layer,
            element = layui.element,
            laytpl = layui.laytpl,
            tree = layui.tree,
            table = layui.treeTable,
            form = layui.form,
            notice = Util.notice !== null && Util.notice() !== null
                ? Util.notice() : layui.notice,
            iziToast = layui.iziToast,
            lodash = _;
        let initOrganizeTree = function () {
            let $treeContainer = $("div.systemauthorizemanage .organizetree");
            httpapi.fetchGet('/api/system/getsystemdatadictree?grouptype=1').then(res => {
                if (!httpapi.checkResponse(res))
                    //输入信息校验错误
                    notice.error(res.message);
                else {//Success
                    tree.render({
                        elem: $treeContainer,
                        id: "systemorganizetree",
                        onlyIconControl: true,
                        data: res.data,
                        click: function (obj) {
                            if (obj.data.pid !== 0)
                                initRolesTrees(obj.data.id);
                            else initRolesTrees();
                        }
                    });
                }
            }).catch(error => notice.error("对不起，出现未知错误，请您联系系统管理员！"));
        },
            cachedroleModels = [],
            initRolesTrees = function (organizeId) {
                let $rolestreeContainer = $("div#roleslist"),
                    roleTpl = document.getElementById("roleslistTpl").innerHTML;
                if (cachedroleModels.length === 0) {
                    let apiurl = "/api/backend/account/getadminroles",
                        index = layer.load(2, { time: 10 * 1000 });
                    httpapi.fetchGet(apiurl).then(res => {
                        layer.close(index);
                        if (!httpapi.checkResponse(res))
                            //输入信息校验错误
                            notice.error(res.message);
                        else {//Success
                            cachedroleModels = lodash.clone(res.data);
                            laytpl(roleTpl).render(cachedroleModels, function (html) {
                                $rolestreeContainer.html(html);
                            });
                        }
                    }).catch(error => {
                        console.error(error);
                        notice.error("对不起，出现未知错误，请您联系系统管理员！")
                    });
                } else {
                    let rolesdata = [];
                    if (typeof organizeId !== "undefined") {
                        let result = lodash.filter(cachedroleModels, function (o) { return o.FKOrganizeId === organizeId; });
                        if (typeof result === "undefined") rolesdata = [];
                        else rolesdata = lodash.concat(rolesdata, result);
                        //else if (lodash.isArray(result)) rolesdata = result;
                        //else if (typeof result === "object") rolesdata.push(result);
                    }
                    else rolesdata = cachedroleModels;
                    laytpl(roleTpl).render(rolesdata, function (html) {
                        $rolestreeContainer.html(html);
                    });
                }
            };

        initOrganizeTree();
        initRolesTrees();
        var authorizetreetableconfig = {
            elem: '#systemauthorizetable',
            tree: {
                iconIndex: 1,  // 折叠图标显示在第几列
                idName: 'Id',  // 自定义id字段的名称
                pidName: 'ParentId',  // 自定义标识是否还有子节点的字段名称
                isPidData: true  // 是否是pid形式数据
            },
            cols: [
                { field: 'Id', title: 'ID', width: 50 },
                { field: 'DisplayName', title: '名称', width: 280 },
                { field: 'IsActive', title: '模块权限', templet: '#isActiveTpl', align: 'center', width: 130 },
                {
                    title: '模块操作权限',
                    templet: function (d) {
                        if (d.ModuleAssignedButtonsDic !== null) {
                            let outputHtml = '',
                                ibtnid = 0;
                            $.each(d.ModuleAssignedButtonsDic, function (btnid, btntitle) {
                                if (typeof btnid === "string") ibtnid = parseInt(btnid);
                                else ibtnid = btnid;
                                outputHtml += '<input type="checkbox" lay-skin="primary" name="buttonauthorize" lay-filter="modulebtnauthorize" title="' + btntitle + '" value="' + ibtnid + '"';
                                if (d.ModuleAuthorizedButtons !== null && lodash.indexOf(d.ModuleAuthorizedButtons, ibtnid) >= 0) {
                                    outputHtml += " checked />";
                                } else outputHtml += " />";
                            });
                            return outputHtml;
                        } else return '';
                    },
                    singleLine: false
                }
            ],
            data: null
        },
            authorizeTableIns = null,
            authorizeChangeWithoutSave = false,
            changeRoleAuthorizeTable = function (othis) {
                authorizeChangeWithoutSave = false;
                $(".list-items li.list-item").removeClass("active");
                othis.addClass("active");
                let apiurl = "/api/system/getsystemmoduleauthorizedatabyroleid?rid=" + othis.find("a").data('id'),
                    index = layer.load(2, { time: 10 * 1000 });
                httpapi.fetchGet(apiurl).then(res => {
                    layer.close(index);
                    if (!httpapi.checkResponse(res))
                        //输入信息校验错误
                        notice.error(res.message);
                    else {//Success
                        authorizetreetableconfig.data = res.data;
                        if (authorizeTableIns === null)
                            authorizeTableIns = table.render(authorizetreetableconfig);
                        else
                            authorizeTableIns.reload(authorizetreetableconfig);
                        authorizeTableIns.expandAll();
                    }
                }).catch(error => notice.error("对不起，出现未知错误，请您联系系统管理员！"));
            };
        $('#roleslist').on('click', 'li.list-item', function () {
            let othis = $(this);
            if (authorizeChangeWithoutSave) {
                layer.confirm('还未提交修改保存，是否放弃?', { icon: 3, title: '提示' }, function (index) {
                    layer.close(index); //注意执行顺序，否则弹出框无法关闭
                    changeRoleAuthorizeTable(othis);
                });
                return false;
            } else changeRoleAuthorizeTable(othis);
        });

        form.on('switch(systemmoduleauthorize)', function (data) {
            authorizeChangeWithoutSave = true;
            $("input[name='moduleauthorize']").removeClass("touched");
            refreshAuthorizeTableStatus($(data.elem));
            form.render();
        });
        //监听顶部按钮栏
        var PageButtonEvent = {
            Save: function (buttonid) {
                var roleid = $("#roleslist li.active").find("a").data("id");
                if (typeof roleid === "undefined") {
                    notice.error("请先选择用户角色");
                    return false;
                }
                var postData = getAuthorizeData();
                authorizeChangeWithoutSave = false;
                iziToast.loading("提交中，请稍候");
                httpapi.fetchPost('/api/system/authorize/edit?rid=' + roleid, postData).then(res => {
                    iziToast.destroy();
                    if (!httpapi.checkResponse(res)) {
                        //输入信息校验错误
                        notice.error(res.message);
                    } else {//Success
                        iziToast.loading(res.message);
                        $.wait(2000).then(function () {
                            Util.MainWindowRedirect("/backend");
                        });
                    }
                }).catch(error => notice.error("对不起，登录过程出现未知错误，请您联系系统管理员！"));

                return false;
            }
        };
        $('.pagebuttongroup .layui-btn').on('click', function (e) {
            e.preventDefault();
            var type = $(this).data('type');
            var buttonid = $(this).data("buttonid");
            PageButtonEvent[type] ? PageButtonEvent[type].call(this, buttonid) : '';
        });

        let getAuthorizeData = function () {
            let authorizeList = [],
                $trRow = null, $modulebtns = null;
            $("input[name='moduleauthorize']").each(function () {
                //moduleModel与后端 SystemModuleModel结构相同
                let moduleModel = { Id: 0, IsActive: 0, ModuleAssignedButtons: [], ModuleAuthorizedButtons: [] };
                moduleModel.Id = $(this).val();
                if ($(this).is(":checked")) moduleModel.IsActive = 1;
                $trRow = $(this).parents("tr:eq(0)");
                $modulebtns = $trRow.find("input[name='buttonauthorize']");
                if ($modulebtns.length > 0) {
                    let btnid = 0;
                    $modulebtns.each(function () {
                        btnid = parseInt($(this).val());
                        moduleModel.ModuleAssignedButtons.push(btnid);
                        if ($(this).is(":checked"))
                            moduleModel.ModuleAuthorizedButtons.push(btnid);
                    });
                }
                authorizeList.push(moduleModel);
            });
            return authorizeList;
        },
            refreshAuthorizeTableStatus = function ($node) {
                //父节点状态影响所有子节点状态
                $node.addClass("touched");
                let nodeCheckStatus = $node.is(":checked");
                if (!nodeCheckStatus) {
                    let $trRow = $node.parents("tr:eq(0)"),
                        $modulebtns = $trRow.find("input[name='buttonauthorize']");
                    if ($modulebtns.length > 0) {
                        $modulebtns.each(function () {
                            //console.log($(this).attr('title'));
                            $(this).prop("checked", false);
                        });
                    }
                }
                let $moduleCheckboxes = $("input[name='moduleauthorize']"),
                    parents = [], childrens = [], siblings = [],
                    triggerParent = true;
                $moduleCheckboxes.each(function () {
                    let $_ = $(this);
                    if ($_.data("id") !== $node.data("id")) { //排除相同节点
                        if ($_.data("pid") === $node.data("id") && !$_.hasClass("touched")) childrens.push($_);
                        else if ($_.data("id") === $node.data("pid") && !$_.hasClass("touched")) {
                            if (nodeCheckStatus) triggerParent = true;
                            else triggerParent = false;
                            parents.push($_);
                        }
                        else if (!triggerParent && $_.data("pid") === $node.data("pid")) {
                            //siblings 同级节点状态和本节点状态全一致(不勾选)，则触发父节点状态不勾选
                            //         同级节点只要有一个状态为勾选，则父节点状态为勾选
                            siblings.push($_);
                            if (nodeCheckStatus !== $_.is(":checked"))
                                triggerParent = false;
                        }

                        if ($_.data("pid") === $node.data("pid"))
                            $_.addClass("touched");
                    } else if (siblings.length === 0) {
                        //没有同级节点，只有节点自己
                        siblings.push($_);
                    }
                });
                if (childrens.length > 0) {
                    $.each(childrens, function (i, $child) {
                        $child.prop("checked", nodeCheckStatus);
                        refreshAuthorizeTableStatus($child);
                    });
                }
                if (!nodeCheckStatus && siblings.length > 0) {
                    let count = 0;
                    $.each(siblings, function (i, $sibling) {
                        if ($sibling.is(":checked") === nodeCheckStatus)
                            count++;
                    });
                    if (count === siblings.length) triggerParent = true;
                }
                if (triggerParent && parents.length > 0) {
                    $.each(parents, function (i, $parent) {
                        $parent.prop("checked", nodeCheckStatus);
                        refreshAuthorizeTableStatus($parent);
                    });
                }
            };
    });//layui.use([
}); //$(function () {